package com.etop.weiway.wxmanage.service;

import com.etop.weiway.basic.service.BaseService;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.dao.AccountDAO;
import com.etop.weiway.wxmanage.dao.WeixinMenuDAO;
import com.etop.weiway.wxmanage.entity.Account;
import com.etop.weiway.wxmanage.entity.WeixinMenu;
import com.etop.weiway.wxmanage.util.WeixinTimeUtil;
import com.etop.weixin.entity.common.AccessToken;
import com.etop.weixin.entity.menu.*;
import com.etop.weixin.utils.MenuUtil;
import com.etop.weixin.utils.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 微信菜单服务类
 * Created by Jeremie on 2014/12/17.
 */
@Service("WeixinMenuService")
public class WeixinMenuService extends BaseService {
    @Autowired
    private WeixinMenuDAO weixinMenuDAO;
    @Autowired
    private AccountDAO accountDAO;


    /**
     * 使用id获得微信菜单
     *
     * @param id
     * @return
     */
    public WeixinMenu loadWeixinMenu(int id) throws Exception {
        log.debug("******使用id获得微信菜单******");
        Map<String, Object> params = createParamMap();
        params.put("id", id);
        String queryString = "from WeixinMenu t where t.valid = 1 and id =:id";
        return weixinMenuDAO.findUniqueResult(queryString, params);
    }

    /**
     * 使用menuKey获得微信菜单
     *
     * @param menuKey
     * @return
     */
    public WeixinMenu loadWeixinMenuByMenuKey(String menuKey) throws Exception {
        log.debug("******使用menuKey获得微信菜单******");
        Map<String, Object> params = createParamMap();
        params.put("menuKey", menuKey);
        String queryString = "from WeixinMenu t where t.valid = 1 and t.menuKey =:menuKey";
        return weixinMenuDAO.findUniqueResult(queryString, params);
    }

    /**
     * 获取父菜单
     *
     * @return
     */
    public List<WeixinMenu> getParentWeinxinMenu(int accountId,int currentParentId) throws Exception {
        log.debug("******获取父菜单******");
        String queryString = "from WeixinMenu t where t.valid = 1 and t.isParent = 1 and t.account.id = "+accountId;
        List<WeixinMenu> weixinMenus = weixinMenuDAO.find(queryString);
        for (int i = weixinMenus.size() -1; i >= 0; i--) {
            WeixinMenu weixinMenu = weixinMenus.get(i);
            queryString = "from WeixinMenu t where t.valid = 1 and t.parent.id = " + weixinMenu.getId();
            if (!(weixinMenu.getId()==currentParentId) && weixinMenuDAO.getTotalCount(queryString)>=5){
                weixinMenus.remove(weixinMenu);
            }
        }
        return weixinMenus;
    }


    /**
     * 保存或更新微信菜单
     *
     * @param weixinMenu
     */
    public void saveWeixinMenu(WeixinMenu weixinMenu,int parentId) throws Exception {
        log.debug("******保存或更新微信菜单******");
        WeixinMenu parent = new WeixinMenu();
        parent.setId(parentId);
        weixinMenu.setParent(parent);
        if(StringUtils.isEmpty(weixinMenu.getMenuType())) {
            weixinMenu.setIsParent((short) 1);
            weixinMenu.setParent(null);
        } else {
            if(parentId==0)
                weixinMenu.setParent(null);
            weixinMenu.setIsParent((short) 0);
        }
        weixinMenuDAO.saveOrUpdate(weixinMenu);
    }

    /**
     * 根据id删除微信菜单(假删除)
     *
     * @param id
     */
    public void deleteWeixinMenuById(int id) throws Exception {
        log.debug("******根据id删除微信菜单******");
        WeixinMenu weixinMenu = new WeixinMenu();
        weixinMenu.setId(id);
        weixinMenuDAO.invalid(weixinMenu);
    }

    /**
     * 分页查询微信菜单
     *
     * @param pager
     * @return pager<WeixinMenu>
     * @throws Exception
     * @Pager keyword
     */
    public Pager<WeixinMenu> getWeixinMenuByPage(Pager<WeixinMenu> pager, String keyword, int accountId) throws Exception {
        log.debug("******分页查询微信菜单******");
        //获取父菜单
        Map<String, Object> params = createParamMap();
        String queryString = "from WeixinMenu t where t.valid = 1 and t.account.id = :accountId and t.parent = null";
        params.put("accountId", accountId);
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.title like :keyword )";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.orderId asc , t.id asc";
        List<WeixinMenu> returnList = new ArrayList<>();
        List<WeixinMenu> weixinMenus = weixinMenuDAO.find(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        //获取子菜单，并排序
        for (WeixinMenu weixinMenu : weixinMenus) {
            if (weixinMenu.getIsParent() == 1) {
                returnList.add(weixinMenu);
                List<WeixinMenu> subWeixinMenus = weixinMenu.getSubWeixinMenu();

                //排序
                Collections.sort(subWeixinMenus, (o1, o2) ->
                        o1.getOrderId().equals(o2.getOrderId())
                                ? o1.getId() - o2.getId()
                                : o1.getOrderId() - o2.getOrderId());

                subWeixinMenus.stream().filter(subWeixinMenu -> subWeixinMenu.getValid() == 1).forEach(subWeixinMenu -> {
                    subWeixinMenu.setTitle("├──" + subWeixinMenu.getTitle());
                    returnList.add(subWeixinMenu);
                });
            } else
                returnList.add(weixinMenu);

        }
        pager.setCount(weixinMenuDAO.getTotalCount(queryString, params));
        pager.setList(returnList);
        return pager;
    }

    /**
     * 获取用于生成的微信菜单
     *
     * @return
     */
    public List<WeixinMenu> getWeixinMenuByAccountId(Integer accountId) throws Exception {
        log.debug("******查询微信菜单******");
        //获取父菜单
        Map<String, Object> params = createParamMap();
        String queryString = "from WeixinMenu t where t.valid = 1 and t.account.id = :accountId and t.parent = null";
        params.put("accountId", accountId);
        queryString += " order by t.orderId asc , t.id asc";
        List<WeixinMenu> returnList = new ArrayList<>();
        List<WeixinMenu> weixinMenus = weixinMenuDAO.find(queryString, params);
        //获取子菜单，并排序
        int j = 0;
        for (WeixinMenu weixinMenu : weixinMenus) {
            if (weixinMenu.getIsParent() == 1) {
                returnList.add(weixinMenu);
                List<WeixinMenu> subWeixinMenus = weixinMenu.getSubWeixinMenu();
                //排序
                Collections.sort(subWeixinMenus, (o1, o2) ->
                        o1.getOrderId().equals(o2.getOrderId())
                                ? o1.getId() - o2.getId()
                                : o1.getOrderId() - o2.getOrderId());
                int i = 0;
                for (WeixinMenu subWeixinMenu : subWeixinMenus)
                    if (subWeixinMenu.getValid() == 1) {
                        subWeixinMenu.setTitle(subWeixinMenu.getTitle());
                        returnList.add(subWeixinMenu);
                        i++;
                        if (i >= 5)
                            break;
                    }
            } else
                returnList.add(weixinMenu);
            j++;
            if (j >= 3)
                break;
        }
        return returnList;
    }

    /**
     * 生成微信菜单并且提交
     *
     * @param menus
     * @param accountId
     * @return
     * @throws Exception
     */
    public Map<String,String> generateWeixinMenu(List<WeixinMenu> menus, Integer accountId) throws Exception {
        Map<String,String > map = new HashMap<>();
        log.debug("******生成微信菜单并且提交******");
        int i = 0;
        Menu menu = new Menu();
        ArrayList<Button> buttonArrayList = new ArrayList<>();
        for (WeixinMenu weixinMenu : menus) {
            if (weixinMenu.getIsParent() == 1) {
                ComplexButton complexButton = new ComplexButton();
                complexButton.setName(weixinMenu.getTitle());
                buttonArrayList.add(complexButton);
                i++;
            } else if (weixinMenu.getParent() == null) {
                Button button;
                switch (weixinMenu.getMenuType()) {
                    case "click":
                        ClickButton clickButton = new ClickButton();
                        clickButton.setName(weixinMenu.getTitle());
                        clickButton.setKey(weixinMenu.getMenuKey());
                        button = clickButton;
                        break;
                    case "view":
                        ViewButton viewButton = new ViewButton();
                        viewButton.setName(weixinMenu.getTitle());
                        viewButton.setUrl(weixinMenu.getUrl());
                        button = viewButton;
                        break;
                    default:
                        map.put("type","error");
                        map.put("message","菜单类型错误");
                        return map;
                }
                buttonArrayList.add(button);
                i++;
            } else {
                ComplexButton complexButton = (ComplexButton) buttonArrayList.get(i - 1);
                ArrayList<Button> subButton;
                if (complexButton.getSub_button() != null)
                    subButton = complexButton.getSub_button();
                else
                    subButton = new ArrayList<>();
                Button button;
                switch (weixinMenu.getMenuType()) {
                    case "click":
                        ClickButton clickButton = new ClickButton();
                        clickButton.setName(weixinMenu.getTitle());
                        clickButton.setKey(weixinMenu.getMenuKey());
                        button = clickButton;
                        break;
                    case "view":
                        ViewButton viewButton = new ViewButton();
                        viewButton.setName(weixinMenu.getTitle());
                        viewButton.setUrl(weixinMenu.getUrl());
                        button = viewButton;
                        break;
                    default:
                        map.put("type","error");
                        map.put("message","菜单类型错误");
                        return map;
                }
                subButton.add(button);
                complexButton.setSub_button(subButton);
            }
        }
        menu.setButton(buttonArrayList);
        for(Button button:buttonArrayList)
            if(button instanceof ComplexButton){
                ComplexButton complexButton = (ComplexButton)button;
                if(complexButton.getSub_button() == null) {
                    map.put("type","error");
                    map.put("message","一级菜单必须要有二级菜单");
                    return map;
                }
            }
        Account account = accountDAO.get(accountId);
        if (MenuUtil.createMenu(menu, WeixinTimeUtil.getAccessToken(account))) {
            map.put("type","success");
            map.put("message","创建菜单成功");
            return map;
        }
        else {
            map.put("type","error");
            map.put("message","创建菜单失败");
            return map;
        }
    }


}
